package com.taugin.wechatreader.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.taugin.wechatreader.business.WxReaderBusiness;
import com.taugin.wechatreader.info.WxAppInfo;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.List;

import static com.taugin.wechatreader.utils.Log.TAG;

/**
 * Created by ck01- on 2017/6/12.
 */

public class Utils {

    /**
     * 将字符串进行md5计算
     * @param inStr
     * @return md5字符串
     */
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            Log.d(TAG, "error : " + e);
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = md5Bytes[i] & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }


    public static int execRootCmd(String paramString) {
        return execRootCmd(paramString, null, null);
    }
    /**
     * 执行root命令
     * @param paramString
     */
    public static int execRootCmd(String paramString, StringBuilder out, StringBuilder error) {
        try {
            Process localProcess = Runtime.getRuntime().exec("su");
            DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
            String str = String.valueOf(paramString);
            String cmdString = str + "\n";
            localDataOutputStream.writeBytes(cmdString);
            localDataOutputStream.flush();
            localDataOutputStream.writeBytes("exit\n");
            localDataOutputStream.flush();

            ProgressReader outReader = new ProgressReader(localProcess.getInputStream(), out);
            ProgressReader errorReader = new ProgressReader(localProcess.getErrorStream(), error);
            outReader.start();
            errorReader.start();
            try {
                outReader.join(30 * 1000);
                errorReader.join(30 * 1000);
                Log.d(Log.TAG, "Reader Thread Over.....................");
            } catch (Exception e) {
            }
            localProcess.waitFor();
            return localProcess.exitValue();
        } catch (Exception e) {
            Log.d(TAG, "error : " + e);
        }
        return -1;
    }

    public static int execCmd(String paramString) {
        return execCmd(paramString, null, null);
    }

    public static int execCmd(String paramString, StringBuilder out, StringBuilder error) {
        try {
            Process localProcess = Runtime.getRuntime().exec(paramString);
            ProgressReader outReader = new ProgressReader(localProcess.getInputStream(), out);
            ProgressReader errorReader = new ProgressReader(localProcess.getErrorStream(), error);
            outReader.start();
            errorReader.start();
            try {
                outReader.join(30 * 1000);
                errorReader.join(30 * 1000);
                Log.d(Log.TAG, "Reader Thread Over.....................");
            } catch (Exception e) {
            }
            localProcess.waitFor();
            return localProcess.exitValue();
        } catch (Exception e) {
            Log.d(TAG, "error : " + e);
        }
        return -1;
    }

    private static class ProgressReader extends Thread {
        private InputStream mInputStream;
        private StringBuilder mBuilder;
        public ProgressReader(InputStream is, StringBuilder builder) {
            mInputStream = is;
            mBuilder = builder;
        }

        @Override
        public void run() {
            try {
                int read = 0;
                byte[] buf = new byte[1024];
                while ((read = mInputStream.read(buf)) > 0) {
                    if (mBuilder != null) {
                        mBuilder.append(new String(buf, 0, read));
                    }
                }
                mInputStream.close();
            } catch(Exception e) {

            }
        }
    }

    public static WxAppInfo getWxAppInfo(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pInfo = pm.getPackageInfo(WxReaderBusiness.WX_PKGNAME, 0);
            WxAppInfo wxAppInfo = new WxAppInfo();
            wxAppInfo.setWxVerCode(pInfo.versionCode);
            wxAppInfo.setWxVerName(pInfo.versionName);
            return wxAppInfo;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断当前手机是否有ROOT权限
     * @return
     */
    public static boolean isRoot(){
        boolean bool = false;

        try{
            if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())){
                bool = false;
            } else {
                bool = true;
            }
        } catch (Exception e) {
        }
        return bool;
    }

    public static void copyFile(String oldPath, String newPath) {
        try {
            int byteRead = 0;
            File oldFile = new File(oldPath);
            if (oldFile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
            }
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }
    }

    /**
     * 递归查找制定的文件，并将结果存储在dbFiles
     * @param dbFiles
     * @param file
     * @param fileName
     */
    public static void searchFile(List<File> dbFiles, File file, String fileName) {
        if (dbFiles == null || file == null || TextUtils.isEmpty(fileName)) {
            Log.d(Log.TAG, "--------------------------------------");
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File childFile : files) {
                    searchFile(dbFiles, childFile, fileName);
                }
            }
        } else {
            if (fileName.equals(file.getName())) {
                dbFiles.add(file);
            }
        }
    }

    public static String getImei(Context context) {
        if (context.checkCallingOrSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager. PERMISSION_GRANTED) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        }
        return null;
    }

    public static void copyAssets(Context context, String fileName, String path) {
        try {
            InputStream is = context.getAssets().open(fileName);
            int read = 0;
            byte[] buf = new byte[1024];
            FileOutputStream fos = new FileOutputStream(path);
            while((read = is.read(buf)) > 0) {
                fos.write(buf, 0, read);
            }
            fos.close();
            is.close();
        } catch(Exception e) {
        }
    }

    public static void putString(Context context, String key, String value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString(key, null);
    }

    public static void loadImage(String url, final ImageView imageView) {
        ImageLoader.getInstance().displayImage(url, imageView);
    }
}
